<?php

namespace app\model\order;

use app\base\BaseModel;
use app\model\activity\ActivityGoodsModel;
use app\model\agency\AgencyGoodsModel;
use app\model\goods\GoodsCommonModel;
use app\model\goods\GoodsModel;
use app\model\system\SysConfigModel;
use app\model\user\UserBeanLogModel;
use app\model\user\UserCouponModel;
use app\model\user\UserEarningsPredictModel;
use app\model\user\UserLevelModel;
use app\model\user\UserModel;
use app\model\user\UserSettlementModel;
use think\model\concern\SoftDelete;

/**
 * 模型-OrderItemModel
 * Class OrderItemModel
 * @package app\model
 */
class OrderItemModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'order_item';

    /**
     * 范围查询-order_out_handle_status
     * @param $query
     * @param string $op
     * @param $status
     */
    public function scopeOrderOutHandleStatus($query, $op = '=', $status)
    {
        if (!empty($status)) {
            $query->where('d.out_handle_status', $op, $status);
        }
    }

    /**
     * 范围查询-order_out_handle_status
     * @param $query
     * @param string $status
     * @param int $out_handle_status
     * @param string $op
     */
    public function scopeBetweenStatus($query, $status, $out_handle_status = 0, $op = '<')
    {
        if (!empty($status)) {
            $query->where('order_status', 'between', $status);
        }
        if (!empty($out_handle_status)) {
            $query->where('out_handle_status', $op, $out_handle_status);
        }
    }

    /**
     * 范围查询-create_time
     * @param $query
     * @param $time
     */
    public function scopeCreateTime($query, $time = [])
    {
        if (!empty($time)) {
            $query->where('a.create_time', 'between', $time);
        }
    }

    /**
     * 范围查询-order_status
     * @param $query
     * @param $status
     */
    public function scopeDistributorId($query, $distributor_id)
    {
        if (!empty($distributor_id)) {
            $query->where('a.distributor_id', '=', $distributor_id);
        }
    }


    /**
     * 范围查询-order_number
     * @param $query
     * @param $keyword
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('a.order_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.pay_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.attribute_names', '%' . trim($keyword) . '%', 'OR');
        }
    }

    /**
     * 获取分页列表
     * @param $distributor_id
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param array $time
     * @param string $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPageData($distributor_id, $keyword, $current_page, $list_rows, $time = [], $order = 'a.create_time desc')
    {
        $dataList = $this
            ->alias("a")
            ->join("t_user b", "a.user_id=b.id")
            ->leftJoin("t_order c", "a.order_id=c.id")
            ->leftJoin("t_goods_common g", "a.goods_id=g.goods_id")
            ->leftJoin("t_distributor d", "a.distributor_id=d.id")
            ->field('a.*,b.head_img,b.nick_name,c.take_address,c.take_name,c.take_phone,g.goods_title,g.goods_image,d.name as distributor_name')
            ->distributorId($distributor_id)
            ->keyword($keyword)
            ->createTime($time)
            ->order($order)
            ->where('a.order_status', '>', 1)
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $items = $dataList->items();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $items];
        return $ret;
    }

    /**
     * 获取订单项的数据
     * @param $order_id
     * @param string $pay_sn
     * @return mixed
     */
    public function getChildInfo($order_id, $pay_sn = "")
    {
        //订单项
        if (!empty($pay_sn)) {
            $this->where("order_id", $order_id)->update(['pay_sn' => $pay_sn]);
            $data = $this->where("order_id", $order_id)->select();
        } else {
            $data = $this
                ->alias("c")
                ->leftJoin("t_goods b", "c.goods_id=b.id")
                ->where("c.order_id", $order_id)
                ->field("c.*,b.goods_title,b.goods_img,c.goods_price,c.goods_number,c.goods_type")
                ->select();
        }
        return $data;
    }

    /**
     * 获取用户订单项信息
     * @param $order_id
     * @param array $item_ids
     * @param array $item_number
     * @param bool $is_send 是否已经发货
     * @param string $type
     * @return mixed
     */
    public function getItemsInfo($order_id, $item_ids = [], $item_number = [], $is_send = false, $type = '')
    {
        $model_data = $this->alias("a")->join("t_goods b", "a.goods_id=b.id")->where("a.order_id", $order_id);
        if (!empty($item_ids)) {
            if (is_array($item_ids)) {
                $model_data = $model_data->where('a.id', 'in', $item_ids);
            } else {
                $model_data = $model_data->where('a.id', $item_ids);
            }
        }
        if (!empty($type)) {
            $model_data = $model_data
                ->where("a.out_handle_status", 0);
            // ->where("a.goods_source", $type)
        }
        $data = $model_data
            ->field("a.id,a.goods_id,a.id,a.return_money,a.goods_number,a.send_number,a.goods_source,a.attribute_names,a.attribute_ids,a.goods_special,a.order_status,a.out_handle_status,a.platform_price,a.cost_price,a.goods_price,a.order_total,b.goods_title,b.goods_img")
            ->select();
        $data_list = [];
        foreach ($data as $value) {
            $value['need_number'] = intval($value['goods_number']) - intval($value['send_number']);
            $value['total_cost_price'] = floatval($value['cost_price']) * intval($value['goods_number']);
            if (!empty($item_number)) {
                if (is_array($item_number)) {
                    $value['now_send_number'] = $item_number[intval($value['id'])];
                } else {
                    $value['now_send_number'] = $item_number;
                }
            } else {
                $value['now_send_number'] = $value['goods_number'];
            }
            if ($is_send) {
                if (intval($value['goods_number']) > intval($value['send_number'])) {
                    $data_list[] = $value;
                } else {
                    continue;
                }
            } else {
                $data_list[] = $value;
            }
        }
        return $data_list;
    }

    /**
     * 获取代理商订单项信息
     * @param $order_id
     */
    public function getAgencyItemsInfo($order_id)
    {
        $data = $this
            ->alias("a")
            ->join("t_goods b", "a.goods_id=b.id")
            ->where("a.order_id", $order_id)
            ->field("a.id,a.agency_money,a.goods_number,a.out_handle_status,b.goods_title,b.goods_img")
            ->select();
        return $data;
    }

    /**
     * 获取订单指定商品列表
     * @param $order_id
     * @param $goods_id
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getItemByGoodsId($order_id, $goods_id = '')
    {
        $map = [
            'order_id' => $order_id
        ];
        if (empty($goods_id)) {
            $items = $this->where($map)->select();
        } else {
            if (is_array($goods_id)) {
                $items = $this->where($map)->whereIn('goods_id', implode(',', $goods_id))->select();
            } else {
                $map['goods_id'] = $goods_id;
                $items = $this->where($map)->select();
            }
        }
        if (empty($items)) {
            $items = [];
        }
        return $items;
    }

    /**
     * 退款成功刷新订单项状态
     * @param $order_id
     * @param string $goods_id
     * @return bool
     */
    public function refundEndByGoodsId($order_id, $goods_id = '')
    {
        $map = [
            'order_id' => $order_id
        ];
        $up_data = [
            'out_handle_status' => 5
        ];
        if (empty($goods_id)) {
            $ret = $this->where($map)->update($up_data);
        } else {
            if (is_array($goods_id)) {
                $ret = $this->where($map)->whereIn('goods_id', implode(',', $goods_id))->update($up_data);;
            } else {
                $map['goods_id'] = $goods_id;
                $ret = $this->where($map)->update($up_data);;
            }
        }
        if ($ret !== false) {
            return true;
        }
        return false;
    }

    /**
     *取消订单(恢复库存)
     * @param $order_id
     * @param $item_ids
     * @param $is_cancel
     * @return OrderItemModel|bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancelOrderStore($order_id, $item_ids = [], $is_cancel = true)
    {
        $map = ['order_id' => $order_id];
        $model_temp = $this->where($map);
        if (!empty($item_ids)) {
            $model_temp = $model_temp->where('id', 'in', $item_ids);
        }
        $goods_item = $model_temp->field('goods_type,agency_id,attribute_ids,goods_id,user_id,goods_source,goods_number,user_id')->select();
        if (empty($goods_item)) {
            return false;
        }
        $change = "add";
        $goods_model = new GoodsModel();
        $ret = false;
        foreach ($goods_item as $value) {
            //商品来源 agency 渠道商 system 平台 store 店铺
            $goods_id = $value['goods_id'];
            $attribute_ids = $value['attribute_ids'];
            $goods_source = $value['goods_source'];
            $goods_number = $value['goods_number'];
            if (!empty($value['goods_type'])) {
                $storage = [
                    'storage' => $goods_number,
                    'attribute_ids' => $attribute_ids,
                    'target_id' => 0
                ];
                $operate = [
                    'operate' => 'system',
                    'admin_id' => 0
                ];
                $remark = "平台商品增加库存(取消订单)";
                $ret = $goods_model->changeStore($goods_id, $storage, $change, 0, $operate, $remark);
//                $activity_goods_model = new ActivityGoodsModel();
//                $activity_data = [
//                    'goods_id' => $goods_id,
//                    'attribute_ids' => $attribute_ids,
//                    'storage' => $goods_number,
//                    'target_id' => 1,
//                    'admin_id' => 0,
//                    'remark' => '商品增加库存(取消订单)'
//                ];
//                $ret = $activity_goods_model->changeStore($activity_data, 'add', 0);
//                $order_group_model = new OrderGroupModel();
//                $up_data_gruop = [
//                    'status' => 3
//                ];
//                $ret = $order_group_model->where($map)->update($up_data_gruop);
            } else {
                switch ($goods_source) {
                    case "agency":
                        $storage = [
                            'goods_id' => $goods_id,
                            'storage' => $goods_number,
                            'target_id' => $value['agency_id'],
                            'operate' => 'agency',
                            'admin_id' => 0,
                            'remark' => "代理商商品增加库存(取消订单)"
                        ];
                        $agency_goods_model = new AgencyGoodsModel();
                        $ret = $agency_goods_model->changeStore($storage, $change);
                        break;
                    case "system":
                        $storage = [
                            'storage' => $goods_number,
                            'attribute_ids' => $attribute_ids,
                            'target_id' => 0
                        ];
                        $operate = [
                            'operate' => 'system',
                            'admin_id' => 0
                        ];
                        $remark = "平台商品增加库存(取消订单)";
                        $ret = $goods_model->changeStore($goods_id, $storage, $change, 0, $operate, $remark);
                        break;
                    case "store":
                        $storage = [
                            'storage' => $goods_number,
                            'attribute_ids' => $attribute_ids,
                            'target_id' => 0
                        ];
                        $operate = [
                            'operate' => 'store',
                            'admin_id' => 0
                        ];
                        $remark = "店铺商品增加库存(取消订单)";
                        $ret = $goods_model->changeStore($goods_id, $storage, $change, 0, $operate, $remark);
                        break;
                    case "all":
//                        $storage = [
//                            'goods_id' => $goods_id,
//                            'storage' => $goods_number,
//                            'target_id' => $value['agency_id'],
//                            'operate' => 'agency',
//                            'admin_id' => 0,
//                            'remark' => "代理商商品增加库存(取消订单)"
//                        ];
//                        $activity_goods_model = new AgencyGoodsModel();
//                        $ret = $activity_goods_model->changeStore($storage, $change);
//                        $storage = [
//                            'storage' => intval($goods_number) - intval($goods_agency_number),
//                            'target_id' => 0,
//                        ];
//                        $operate = [
//                            'operate' => 'system',
//                            'admin_id' => 0
//                        ];
//                        $remark = "平台商品增加库存(取消订单)";
//                        $ret = $goods_model->changeStore($goods_id, $storage, $change, 0, $operate, $remark);
//                        break;
                    default:

                }
            }
        }
        if ($ret == true && $is_cancel === true) {
            $up_data = [
                'order_status' => 0
            ];
            $order_model = new OrderModel();
            $retx = $order_model->where('id', $order_id)->update($up_data);
            $ret = $this->where(['order_id' => $order_id])->update($up_data);
            if ($ret === false || $retx === false) {
                return false;
            }
            return true;
        }
        return $ret;
    }

    /**
     * 更新支付状态
     * @param $order_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function payOrder($order_id)
    {
        $map = [
            'order_id' => $order_id
        ];
        $order_model = new OrderModel();
        $order_data = $order_model->where('id', $order_id)->find();
        $up_pay = [
            'order_status' => 2,
            'pay_date' => time()
        ];
        $this->startTrans();
        try {
            $ret = $this->where($map)->update($up_pay);
            if ($ret !== false) {
//                $detail = "购买商品获得积分";
//                $system = SysConfigModel::getSystem();
//                $pay_integral = intval($system['pay_integral']);
//                UserModel::changeIntegral($order_data['user_id'], intval($order_data['order_total']) * $pay_integral, 'add', $detail);
                $this->commit();
                $return_data['code'] = 1;
                $return_data['msg'] = "支付成功";
                return $return_data;
            }
        } catch (\Exception $exception) {
            $this->rollback();
        }
        $this->rollback();
        $return_data['code'] = 0;
        $return_data['msg'] = "支付失败";
        return $return_data;
    }

    /**
     * 判断是否发货完成
     * @param string $order_id
     * @param array $order_item
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sendItemEnd($order_id = '', $order_item = [])
    {
        foreach ($order_item as $value) {
            $send_number = intval($value['send_number']) + intval($value['now_send_number']);
            if (intval($value['goods_number']) <= $send_number) {
                $order_item_update = [
                    'id' => $value['id'],
                    'send_number' => intval($value['send_number']) + intval($value['now_send_number']),
                    'order_status' => 3
                ];
            } else {
                $order_item_update = [
                    'id' => $value['id'],
                    'send_number' => intval($value['send_number']) + intval($value['now_send_number'])
                ];
            }
            OrderItemModel::upSendNumber($order_item_update);
        }
        $map = [
            'order_id' => $order_id,
            'out_handle_status' => 0,
            'order_status' => 2
        ];
        $temp = $this->where($map)->find();
        if (empty($temp)) {
            $up_data = [
                'order_status' => 3,
                'send_date' => date("Y-m-d H:i:s")
            ];
            $order_model = new OrderModel();
            $order_model->where(['id' => $order_id])->update($up_data);
            return true;
        }
        return false;
    }

    /**
     * 刷新特殊商品
     * @param $order_id
     * @param int $type
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function upDateGoodsSpecial($order_id, $type = 1)
    {
        $order_list = $this->where(['order_id' => $order_id, 'goods_special' => $type])->field('user_id,goods_id,attribute_ids,goods_number,goods_special')->select();
        if (empty($order_list)) {
            return false;
        }
        foreach ($order_list as $value) {
            if (intval($value['goods_special']) == 3) {
                //刷新大礼包
                $goods_common_model = new GoodsCommonModel();
                $map = [
                    'goods_id' => $value['goods_id'],
                    'attribute_ids' => $value['attribute_ids'],
                ];
                $goods_temp = $goods_common_model->where($map)->find();
                $bean = floatval($goods_temp['bean']) * floatval($value['goods_number']);
                $coupon = $goods_temp['coupon'];
                UserBeanLogModel::changeEarningsBean($value['user_id'], $bean, "recharge", "购买大礼包赠送");
                // 优惠券暂时不赠送
//                if ($coupon > 50) {
//                    for ($i = 0; $i < intval($coupon / 50); $i++) {
//                        UserCouponModel::addCoupon($value['user_id'], 50, 1, "购买大礼包赠送");
//                    }
//                    $coupon_ = $coupon % 50;
//                    if ($coupon_ > 0) {
//                        UserCouponModel::addCoupon($value['user_id'], $coupon_, 1, "购买大礼包赠送");
//                    }
//                } else {
//                    UserCouponModel::addCoupon($value['user_id'], $coupon, 1, "购买大礼包赠送");
//                }
            }
        }
        return false;
    }

    /**
     * 获取用户购买商品数量
     * @param string $goods_id
     * @param string $attribute_ids
     * @param string $user_id
     * @return int
     */
    public static function getBuyNumber($goods_id = '', $attribute_ids = '', $user_id = '')
    {
        $map = [
            'goods_id' => $goods_id,
            'attribute_ids' => $attribute_ids,
            'user_id' => $user_id,
        ];
        $num = self::where($map)->where('order_status', '>', 0)->sum('goods_number');
        if (empty($num)) {
            $num = 0;
        }
        return $num;
    }

    /**
     * 获取发货商家
     * @param string $order_id
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getSendShops($order_id = '')
    {
        $list = self::where(['order_id' => $order_id])->field('goods_source')->select();
        $agency = 0;
        $system = 0;
        foreach ($list as $value) {
            if ($value['goods_source'] == 'agency') {
                $agency++;
            }
            if ($value['goods_source'] == 'system') {
                $system++;
            }
        }
        $goods_source = 1;
        if ($agency == 0) {
            $goods_source = 1;
        }
        if ($system == 0) {
            $goods_source = 2;
        }
        if ($system > 0 && $agency > 0) {
            $goods_source = 3;
        }
        return $goods_source;
    }

    /**
     * 更新发货库存
     * @param $up_date
     * @return mixed
     */
    public static function upSendNumber($up_date)
    {
        $ret = self::where('id', $up_date['id'])->update($up_date);
        return $ret;
    }

    /**
     * 获取退款订单项总金额
     * @param string $order_id
     * @return float
     */
    public static function getRefundMoney($order_id = '')
    {
        $order_total = self::where(['order_id' => $order_id])->where('out_handle_status', '>', 0)->where('out_type', '>', 0)->sum('order_total');
        return round($order_total, 2);
    }

    /**
     * 获取退款订单项总金额
     * @param string $order_id
     * @return float
     */
    public static function getRefundCostMoney($order_id = '')
    {
        $order_total = self::where(['order_id' => $order_id])->where('out_handle_status', '>', 0)->where('out_type', '>', 0)->sum('cost_price*goods_number');
        return round($order_total, 2);
    }

    /**
     * 判断item_id 发货方 返回对于的发货方
     * @param $order_id
     * @param array $item_ids
     * @param string $goods_source
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSystemAgency($order_id, $item_ids = [], $goods_source = 'system')
    {
        $map = [
            'order_id' => $order_id,
            'goods_source' => $goods_source
        ];
        if (!empty($item_ids)) {
            $order_item_list = $this->where($map)->where('id', 'in', $item_ids)->field('id')->select();
        } else {
            $order_item_list = $this->where($map)->field('id')->select();
        }
        $item_ids_return = [];
        foreach ($order_item_list as $value) {
            $item_ids_return[] = $value['id'];
        }
        return $item_ids_return;
    }

    /**
     * 获取结算订单
     * @param $start_time
     * @param $end_time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getSettleSale()
    {
        $map = [
            'goods_type' => 0,
            'out_type' => 0,
            'settlement' => 0,//无结算的
        ];
        $list = self::where('order_status', '>', 3)->where($map)->field('id,create_time,user_id,(goods_price*goods_number) as price_all,channel_money')->select();
        if (empty($list)) {
            return [];
        }
        $list = json_decode(json_encode($list), true);
        foreach ($list as $value) {
            $day = date("Y-m-d", strtotime($value['create_time']));
            if ($value['channel_money'] > 0) {
                $ret = UserSettlementModel::addSettlement($value['user_id'], $value['price_all'], $day, $value['channel_money']);
                if ($ret) {
                    self::endSettleSale($value['id']);
                }
            } else {
                self::endSettleSale($value['id']);
            }
        }
        return $list;
    }

    /**
     * 完成结算标识
     * @param string $id
     * @return bool
     */
    public static function endSettleSale($id = '')
    {
        $up_data = [
            'settlement' => 1
        ];
        $ret = self::where('id', $id)->update($up_data);
        if ($ret !== false) {
            //清除预结算订单项
            UserEarningsPredictModel::clearEarnings($id);
            return true;
        }
        return false;

    }

    //清除预结算
    public static function clearEarnings($order_id = '')
    {
        $map = [
            'order_id' => $order_id,
            'settlement' => 0
        ];
        $list_item = self::where($map)->field('id')->select();
        foreach ($list_item as $value) {
            UserEarningsPredictModel::clearEarnings($value['id']);
        }
    }
}
